package com.example.netty.客户端登录;

import com.example.netty.encode.Packet.LoginRequestPacket;
import com.example.netty.encode.Packet.LoginResponsePacket;
import com.example.netty.encode.Packet.PackerCode;
import com.example.netty.encode.Packet.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author liupk
 * @date 2018/10/25
 */
public class ServerHandle extends ChannelInboundHandlerAdapter{
    
    
    public ServerHandle() {
        super();
    }
    
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }
    
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        /**解码操作*/
        Packet packet = PackerCode.getINSTANCE().decode(byteBuf);
        /**构建响应对象*/
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        if (packet instanceof LoginRequestPacket){
            LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;
            /**校验登录信息*/
            if (validate(loginRequestPacket)){
                System.out.println("校验成功！");
                loginResponsePacket.setSuccess(true);
                loginResponsePacket.setMsg("账号名密码正确");
            }else {
                System.out.println("校验失败！");
                loginResponsePacket.setSuccess(false);
                loginResponsePacket.setMsg("账号名密码错误");
            }
        }
    
        ByteBuf buf = PackerCode.getINSTANCE().encode(ctx.alloc().ioBuffer(), loginResponsePacket);
        ctx.channel().writeAndFlush(buf);
    }
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }
    
    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        super.channelWritabilityChanged(ctx);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
    
    
    private Boolean validate(LoginRequestPacket loginRequestPacket){
        return true;
    }
}